<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useUserStore } from '@/store/user';
import { UserEnvironment } from '@/api/code/type';
import { router } from '@/router';
import { getUserEnvironmentList } from '@/api/code';
import { startContainer, stopContainer } from '@/api/docker';
import { showNotify, showToast } from 'vant';
import { Result } from '@/utils/request';

const dataList = ref([] as UserEnvironment[])
const loading = ref(true);
const refreshing = ref(false);
const isEmpty = ref(false);

onMounted(() => {
    loadEnvironmentList();
})

const loadEnvironmentList = async () => {
    loading.value = true;
    try {
        const userStore = useUserStore();
        const userId = userStore.getId;
        const res = await getUserEnvironmentList(userId);
        dataList.value = res.data as UserEnvironment[];
        isEmpty.value = dataList.value.length === 0;
    } catch (error) {
        console.error('加载环境列表失败:', error);
        showNotify({
            type: 'danger',
            message: '加载环境列表失败',
            position: 'top'
        });
    } finally {
        loading.value = false;
        refreshing.value = false;
    }
}

const onRefresh = () => {
    refreshing.value = true;
    loadEnvironmentList();
}

const toCode = (item: UserEnvironment) => {
    if (item.status != 'Running') {
        showToast("请先启动编程环境！");
    } else {
        router.push({
            name: 'OnlineCode',
            query: {
                'id': item.id,
            }
        })
    }
}

const toCreate = () => {
    router.push({
        name: 'OnlineCodeCreate'
    })
}

const start = async (item: UserEnvironment, event: Event) => {
    event.stopPropagation();
    
    try {
        const res = await startContainer(item.instance.id, item.containerId);
        item.status = 'Running';
        const {msg} = res as Result;
        showToast({
            message: msg || '环境启动成功',
            position: 'top',
            icon: 'success'
        });
    } catch (error) {
        console.error('启动环境失败:', error);
        showToast({
            message: '启动环境失败，请重试',
            position: 'top',
            icon: 'cross'
        });
    }
}

const stop = async (item: UserEnvironment, event: Event) => {
    event.stopPropagation();
    
    try {
        await stopContainer(item.instance.id, item.containerId);
        item.status = 'Exited';
        showToast({
            message: '环境已停止',
            position: 'top',
            icon: 'success'
        });
    } catch (error) {
        console.error('停止环境失败:', error);
        showToast({
            message: '停止环境失败，请重试',
            position: 'top',
            icon: 'cross'
        });
    }
}
</script>

<template>
    <div class="code-environment-list">
        <div class="page-header">
            <h1 class="page-title">我的编程环境</h1>
            <van-button class="create-button" type="primary" icon="plus" @click="toCreate">新建环境</van-button>
        </div>

        <!-- 下拉刷新 -->
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="environment-list-container">
            <!-- 加载状态 -->
            <div v-if="loading && !refreshing" class="loading-container">
                <van-loading type="spinner" vertical>加载中...</van-loading>
            </div>

            <!-- 空状态 -->
            <div v-else-if="isEmpty" class="empty-container">
                <van-empty 
                    image="search" 
                    description="您还没有创建编程环境" 
                >
                    <template #default>
                        <van-button type="primary" icon="plus" @click="toCreate">创建第一个环境</van-button>
                    </template>
                </van-empty>
            </div>

            <!-- 环境列表 -->
            <div v-else class="environment-cards">
                <div 
                    v-for="(item, index) in dataList" 
                    :key="index"
                    class="environment-card"
                    @click="toCode(item)"
                >
                    <div class="card-header">
                        <span class="environment-name">{{ item.name }}</span>
                        <van-tag 
                            :type="item.status === 'Running' ? 'success' : 'warning'" 
                            class="status-tag"
                        >
                            {{ item.status === 'Running' ? '运行中' : '已停止' }}
                        </van-tag>
                    </div>
                    <div class="card-content">
                        <div class="environment-info">
                            <div class="info-item">
                                <van-icon name="cluster-o" />
                                <span>环境类型：{{ item.environment.name }}</span>
                            </div>
                            <div class="info-item">
                                <van-icon name="server-o" />
                                <span>实例ID：{{ item.instance.name }}</span>
                            </div>
                        </div>
                    </div>
                    <div class="card-actions">
                        <van-button 
                            v-if="item.status === 'Running'" 
                            type="danger" 
                            size="small" 
                            icon="pause-circle-o"
                            @click="stop(item, $event)"
                        >
                            停止环境
                        </van-button>
                        <van-button 
                            v-else 
                            type="primary" 
                            size="small" 
                            icon="play-circle-o"
                            @click="start(item, $event)"
                        >
                            启动环境
                        </van-button>
                        <van-button 
                            type="default" 
                            size="small" 
                            icon="edit" 
                            :disabled="item.status !== 'Running'"
                            @click="toCode(item)"
                        >
                            打开编辑器
                        </van-button>
                    </div>
                </div>
            </div>
        </van-pull-refresh>
    </div>
</template>

<style lang="scss" scoped>
.code-environment-list {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 108px);
    background-color: #f7f8fa;
    
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 24px;
        background-color: white;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        margin-bottom: 16px;
        
        .page-title {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
            color: #323233;
        }
    }
    
    .environment-list-container {
        flex: 1;
        overflow-y: auto;
        padding: 0 16px 16px;
    }
    
    .loading-container,
    .empty-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 400px;
    }
    
    .environment-cards {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 16px;
        
        @media (max-width: 768px) {
            grid-template-columns: 1fr;
        }
        
        .environment-card {
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            cursor: pointer;
            
            &:hover {
                transform: translateY(-4px);
                box-shadow: 0 8px 16px rgba(0, 0, 0, 0.09);
            }
            
            .card-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px;
                background-color: #f8f8f8;
                border-bottom: 1px solid #f2f3f5;
                
                .environment-name {
                    font-weight: 600;
                    font-size: 16px;
                    color: #323233;
                }
            }
            
            .card-content {
                padding: 16px;
                
                .environment-info {
                    .info-item {
                        display: flex;
                        align-items: center;
                        margin-bottom: 8px;
                        color: #646566;
                        
                        &:last-child {
                            margin-bottom: 0;
                        }
                        
                        .van-icon {
                            margin-right: 8px;
                            color: #969799;
                        }
                    }
                }
            }
            
            .card-actions {
                display: flex;
                justify-content: flex-end;
                gap: 8px;
                padding: 12px 16px;
                background-color: #f8f8f8;
                border-top: 1px solid #f2f3f5;
            }
        }
    }
}
</style>